package com.haredot.event.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.haredot.constraint.RedisConst;
import com.haredot.entity.Message;
import com.haredot.entity.UserBlack;
import com.haredot.event.RssMessageEvent;
import com.haredot.mapper.MessageMapper;
import com.haredot.mapper.UserBlackMapper;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.time.ZoneOffset;

@Component
public class RssMessageEventListener implements ApplicationListener<RssMessageEvent> {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private UserBlackMapper userBlackMapper ;

    @Resource
    private RedisTemplate<String, Message> redisTemplate;

    @Override
    public void onApplicationEvent(RssMessageEvent event) {
        // 获取到 消息
        Message message = event.getMessage();
        // 判断该用户是否在 对方的 好友黑名单中
        boolean black = userBlackMapper.exists(new LambdaQueryWrapper<UserBlack>()
                .eq(UserBlack::getUserId, message.getToUser())
                .eq(UserBlack::getBlackUser, message.getFromUser())) ;

        if (!black) {
            // 将消息写入到数据库表中 (未读状态)
            messageMapper.insert(message);
            // 接收用户发送的消息。将消息 以键 chat:fromuser:touser 格式写入到 redis数据库 有序集合中， score 为 写入的时间
            String redisKey = MessageFormat.format(RedisConst.CHAT_MESSAGE_TEMPLATE,
                    String.valueOf(message.getFromUser()), String.valueOf(message.getToUser()));

            redisTemplate.opsForZSet().add(redisKey, message,
                    message.getCreateTime().toInstant(ZoneOffset.UTC).toEpochMilli());
        }
    }
}
